<?php
// 应用公共文件

use app\common\service\AuthService;
use think\facade\Cache;

if (!function_exists('__url')) {

    /**
     * 构建URL地址
     * @param string $url
     * @param array $vars
     * @param bool $suffix
     * @param bool $domain
     * @return string
     */
    function __url(string $url = '', array $vars = [], $suffix = true, $domain = false)
    {
        return url($url, $vars, $suffix, $domain)->build();
    }
}

if (!function_exists('password')) {

    /**
     * 密码加密算法
     * @param $value 需要加密的值
     * @param $type  加密类型，默认为md5 （md5, hash）
     * @return mixed
     */
    function password($value)
    {
        $value = sha1('blog_') . md5($value) . md5('_encrypt') . sha1($value);
        return sha1($value);
    }

}

if (!function_exists('xdebug')) {

    /**
     * debug调试
     * @param string|array $data 打印信息
     * @param string $type 类型
     * @param string $suffix 文件后缀名
     * @param bool $force
     * @param null $file
     */
    function xdebug($data, $type = 'xdebug', $suffix = null, $force = false, $file = null)
    {
        !is_dir(runtime_path() . 'xdebug/') && mkdir(runtime_path() . 'xdebug/',true);
        if (is_null($file)) {
            $file = is_null($suffix) ? runtime_path() . 'xdebug/' . date('Ymd') . '.txt' : runtime_path() . 'xdebug/' . date('Ymd') . "_{$suffix}" . '.txt';
        }
        file_put_contents($file, "[" . date('Y-m-d H:i:s') . "] " . "========================= {$type} ===========================" . PHP_EOL, FILE_APPEND);
//        $str = (is_string($data) ? $data : (is_array($data) || is_object($data)) ? print_r($data, true) : var_export($data, true)) . PHP_EOL;
        $str = ((is_string($data) ? $data : (is_array($data) || is_object($data))) ? print_r($data, true) : var_export($data, true)) . PHP_EOL;
        $force ? file_put_contents($file, $str) : file_put_contents($file, $str, FILE_APPEND);
    }
}

if (!function_exists('sysconfig')) {

    /**
     * 获取系统配置信息
     * @param $group
     * @param null $name
     * @return array|mixed
     */
    function sysconfig($group, $name = null)
    {
        $where = ['group' => $group];
        $value = empty($name) ? Cache::get("sysconfig_{$group}") : Cache::get("sysconfig_{$group}_{$name}");
        $value = null;
        if (empty($value)) {
            if (!empty($name)) {
                $where['name'] = $name;
//                $value = \app\admin\model\SystemConfig::where($where)->value('value');
                $values = \app\admin\model\SystemConfig::where($where)->findOrEmpty()->toArray();
                if($values['formtype']=='checkbox'){
                    $value = explode('|',$values['value']??'');
                }else{
                    $value = $values['value']??'';
                }
                Cache::tag('sysconfig')->set("sysconfig_{$group}_{$name}", $value, 3600);
            } else {
//                $value = \app\admin\model\SystemConfig::where($where)->column('value', 'name');
                $values = \app\admin\model\SystemConfig::where($where)->select()->each(function ($item){
                    if($item['formtype']=='checkbox'){
                        $item['value'] = explode('|',$item['value']??'');
                    }
                    return $item;
                })->toArray();
                $data = array_column($values,'value');
                $key = array_column($values,'name');
                $value = array_combine($key,$data);
                Cache::tag('sysconfig')->set("sysconfig_{$group}", $value, 3600);
            }
        }
        return $value;
    }
}

if (!function_exists('array_format_key')) {

    /**
     * 二位数组重新组合数据
     * @param $array
     * @param $key
     * @return array
     */
    function array_format_key($array, $key)
    {
        $newArray = [];
        foreach ($array as $vo) {
            $newArray[$vo[$key]] = $vo;
        }
        return $newArray;
    }

}

if (!function_exists('auth')) {

    /**
     * auth权限验证
     * @param $node
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function auth($node = null)
    {
        $authService = new AuthService(session('admin.id'));
        $check = $authService->checkNode($node);
        return $check;
    }

}

if(!function_exists('getDataBaseConfig')){
    /**获取数据库配置
     * @param string $str
     * @return mixed
     */
    function getDataBaseConfig($str='')
    {
        if(empty($str)){
            $array = config('database.connections.'.config('database.default'));
        }else{
            $array = config('database.connections.'.config('database.default').'.'.$str);
        }
        return $array;
    }
}
if(!function_exists('getAppFilePath')){
    /**获取数据库配置
     * @param string $str
     * @return mixed
     */
    function getAppFilePath(string $str,bool $is_array=false)
    {
        if(empty($str)){
            if($is_array){
                return [];
            }else{
                return '';
            }
        }
        $array = explode(',',$str);
        if(count($array)==1){
            $array = explode('|',$array[0]);
        }
        $newdata = [];
        foreach ($array as $value){
            if(strpos($value,'http')===false){
                $newdata[] = request()->domain().'/'.trim($value,'/');
            }else{
                $newdata[] = $value;
            }
        }
        if($is_array){
            return  $newdata;
        }else{
            return $newdata[0];
        }
    }
}
/**
 * 获取用户ip
 */
if(!function_exists('getIp')){
    function getIp()
    {
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
            $ip = getenv("HTTP_CLIENT_IP");
        else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
            $ip = getenv("REMOTE_ADDR");
        else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
            $ip = $_SERVER['REMOTE_ADDR'];
        else
            $ip = "unknown";
        return($ip);
    }
}
/**
 * api返回数据
 */
if(!function_exists('ret_json')){
    function ret_json($msg='',$data=[],$status=200){
        $newdata = [
            'code'=>$status,
            'msg'=>$msg,
            'data'=>$data,
            ];
        return json($newdata);
    }
}
/**
 * api成功返回
 */
if(!function_exists('api_success')){
    function api_success($msg='',$data=[],$status=200){
        $newdata = [
            'code'=>$status,
            'msg'=>$msg,
            'data'=>$data,
        ];
        return json($newdata);
    }
}
/**
 * api失败返回
 */
if(!function_exists('api_fail')){
    function api_fail($msg='',$status=205,$data=[]){
        if(empty($data)){
            $newdata = [
                'code'=>$status,
                'msg'=>$msg,
//                'data'=>$data,
            ];
        }else{
            $newdata = [
                'code'=>$status,
                'msg'=>$msg,
                'data'=>$data,
            ];
        }
        return json($newdata);
    }
}
/**
 * 获取地址经纬度
 */
if(!function_exists('addressGetLonLat')){
    function addressGetLonLat($address,$region=''){
        $url = "https://apis.map.qq.com/ws/geocoder/v1/?address={$address}&region={$region}&key=ZWEBZ-R7N3U-BJSVH-4TCR3-66MDQ-S3FDJ";
        $data = file_get_contents($url);
        $data = json_decode($data,true);
        return $data;
    }
}
/**
 * 使用curl
 */
if(!function_exists('curl')){
    function curl(string $url,array $data = [],array $header= [],$method='POST',$useCert=false,$sslCertPath='',$sslKeyPath=''){
        $oCurl = curl_init();

        curl_setopt($oCurl,CURLOPT_URL,$url);

        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);

//关闭https验证

        if($useCert){
            curl_setopt($oCurl,CURLOPT_SSL_VERIFYPEER,TRUE);
            curl_setopt($oCurl,CURLOPT_SSL_VERIFYHOST,2);//严格校验
            curl_setopt($oCurl,CURLOPT_SSLCERTTYPE,'PEM');
            curl_setopt($oCurl,CURLOPT_SSLCERT, $sslCertPath);
            curl_setopt($oCurl,CURLOPT_SSLKEYTYPE,'PEM');
            curl_setopt($oCurl,CURLOPT_SSLKEY,$sslKeyPath);
        }else{
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, false);

            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
        }

//        $data = json_encode( $data ,JSON_UNESCAPED_UNICODE );
        if(strtoupper($method)=="POST"){
//            echo 1;exit;
            curl_setopt($oCurl,CURLOPT_POST,true);
            curl_setopt($oCurl, CURLOPT_CUSTOMREQUEST, 'POST');
        }elseif (strtoupper($method)=="PUT"){
            curl_setopt($oCurl, CURLOPT_CUSTOMREQUEST, 'PUT');
        }elseif (strtoupper($method)=="DELETE"){
            curl_setopt($oCurl, CURLOPT_CUSTOMREQUEST, 'DELETE');
        }elseif (strtoupper($method)=="GET"){
            curl_setopt($oCurl, CURLOPT_CUSTOMREQUEST, 'GET');
            curl_setopt($oCurl,CURLOPT_POST,false);
        }
        if(!empty($data)){
            try{
                curl_setopt($oCurl,CURLOPT_POSTFIELDS,$data);
            }catch (Exception $e){
                try{
                    curl_setopt($oCurl,CURLOPT_POSTFIELDS,http_build_query($data));
                }catch (\Exception $e){
                    $data = json_encode( $data ,JSON_UNESCAPED_UNICODE );
                    curl_setopt($oCurl,CURLOPT_POSTFIELDS,$data);
                }
            }
//            curl_setopt($oCurl,CURLOPT_POSTFIELDS,$data);
        }
        if(empty($header)){
            curl_setopt($oCurl,CURLOPT_HEADER,false);
        }else{
            curl_setopt($oCurl,CURLOPT_HEADER,$header);
        }


        //至关重要，CURLINFO_HEADER_OUT选项可以拿到请求头信息

        curl_setopt($oCurl, CURLINFO_HEADER_OUT, TRUE);

        $sContent = curl_exec($oCurl);
        //通过curl_getinfo()可以得到请求头的信息

        $a=curl_getinfo($oCurl);
        if($error=curl_errno($oCurl)){
            //            $this->message = $error;
            return [false,$error];
        }
        return [true,$sContent];
    }
}
/**
 * 获取json的配置
 */
if(!function_exists('getJsonConfig')){
    function getJsonConfig($str=''){
        if(empty($str)){
            return '';
        }
        $str_array = explode('.',$str);
//        echo '<pre>';
//        print_r($str_array);
//        exit;
        $dir = config_path();
        foreach ($str_array as $value){
            $dir .= $value;
            if(is_dir($dir)){
                $dir.=DIRECTORY_SEPARATOR;
                continue;
            }
            if(is_file($dir.'.json')){
                $array = json_decode(file_get_contents($dir.'.json'),true);
                continue;
            }
            if(isset($array[$value])){
                $array = $array[$value];
            }else{
                $array = '';
            }
        }
        if(isset($array)){
            return $array;
        }else{
            return '';
        }

    }
}
if(!function_exists('SpanConfig')){
    function SpanConfig($str=''){
        $str_array = explode('.',$str);
        $dir = base_path();
        $array = [];
        foreach ($str_array as $value){
            $dir .= $value;
            if(is_dir($dir)){
                $dir .= DIRECTORY_SEPARATOR;
                continue;
            }elseif (is_file(rtrim($dir,'.php').'.php')){
                $array = include rtrim($dir,'.php').'.php';
            }
            if(isset($array[$value])){
                $array = $array[$value];
            }
        }
        return $array;
    }
}
/**
 * 获取订单号
 */
if(!function_exists('getOrder')){
    function getOrder($user_id,$prefix=''){
        $str = $prefix.date('ymd').uniqid($user_id);
        return $str;
    }
}